'''
/**
 * tlv: a protocol at transport layer.
 * --------------------------------
 * |  T:4   |  L:4   |  V:($L)  |
 * --------------------------------
 * auther: neal.mei
 *     neal.mei.rf@gmail.com
 */
'''

import struct



def tlv_add(buf, offset, T, L, V):
    buf += struct.pack('i', T);
    offset += 4;
    
    buf += struct.pack('i', L);
    offset += 4;
    
    if L==4 and type(V)==type(1):
        buf += struct.pack('i', V);
        offset += L;
        return (buf, offset);
    
    if type(V)==type('str') and len(V) != L:
        print 'len(V) should be equal with $L'
        return None

    buf += struct.pack('%ds'%L, V[0:L]);
    offset += L;
    
    return (buf, offset);


    
def tlv_get(buf, T):
    L = 0;
    V = '';

    offset = 0;
    while offset < len(buf):
        tmp_T = struct.unpack('i', buf[offset:(offset+4)])[0];
        offset += 4;
        tmp_L = struct.unpack('i', buf[offset:(offset+4)])[0];
        offset += 4;

        if tmp_T != T:
            offset += tmp_L;
            continue;

        tmp_V = struct.unpack('%ds'%tmp_L, buf[offset:(offset+tmp_L)])[0];
        offset += tmp_L;

        L = tmp_L;
        V = tmp_V;
        return (L, V);

    print 'data not found in buf, T=', T
    return (None, None);
        
    
